package com.zby.lease.web.admin.custom.interceptor;

import com.zby.lease.common.Login.LoginUser;
import com.zby.lease.common.Login.LoginUserHolder;
import com.zby.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
//       拦截器 拦截请求，返回true表示继续流程，返回false表示流程中断，不会继续执行下一个拦截器或者controller
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       设置请求头为access-token
        String token = request.getHeader("access-token");
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId, username));

//        JwtUtil.parseToken(header);
        return true;
    }

    @Override
//       拦截器 渲染视图之前执行，返回true表示继续流程，返回false表示流程中断，不会继续执行下一个拦截器或者controller
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
//       拦截器 渲染视图之后执行，返回true表示继续流程，返回false表示流程中断，不会继续执行下一个拦截器或者controller
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    LoginUserHolder.removeLoginUser();
    }
}
